# coding=utf-8
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from backstage.vows.utils import view_funcs


class VowList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAdminUser,)

    def get(self, request):
        """
        获取发愿文列表
        """
        vows = view_funcs.get_vow_list()
        return Response({
            "status": 200,
            "msg": "success",
            "data": vows,
        })

    def post(self, request):
        """
        新建发愿文
        """
        name = request.data.get("name")
        content = request.data.get("content")
        if not name or not content:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        view_funcs.create_vow(name, content)
        return Response({
            "status": 200,
            "msg": "success",
        })


class VowDetail(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAdminUser,)

    def get(self, request, vow_id):
        """
        获取发愿文
        """
        vow_data = view_funcs.get_vow(vow_id)
        if not vow_data:
            return Response({
                "status": 404,
                "msg": "not found",
            })
        return Response({
            "status": 200,
            "msg": "success",
            "data": vow_data,
        })

    def delete(self, request, vow_id):
        """
        删除发愿文
        """
        view_funcs.delete_vow(vow_id)
        return Response({
            "status": 200,
            "msg": "success",
        })

    def put(self, request, vow_id):
        """
        更新发愿文
        """
        name = request.data.get("name")
        content = request.data.get("content")
        if not name or not content:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        view_funcs.update_vow(vow_id, name, content)
        return Response({
            "status": 200,
            "msg": "success",
        })
